import { Injectable } from '@nestjs/common';
import { CreateUserErrorDto } from './dto/create-user_error.dto';
import { UpdateUserErrorDto } from './dto/update-user_error.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserError } from './entities/user_error.entity';
import { Exebook } from 'src/modules/questionbank/exebook/entities/exebook.entity';
import { User } from 'src/modules/system/user/entities/user.entity';  
@Injectable()
export class UserErrorService {
  constructor(
    @InjectRepository(UserError)
    private usersErrorRepository: Repository<UserError>
  ) {}
  async create(createUserErrorDto: CreateUserErrorDto) {
    const exe=new Exebook();
    exe.Id=createUserErrorDto.exeId;
    const user=new User();
    user.Id=createUserErrorDto.userId;
    const usererror = this.usersErrorRepository.create(createUserErrorDto);
    usererror.exe=exe;
    usererror.user=user;
    console.log(usererror);
    await this.usersErrorRepository.save(usererror);
    return usererror;
  }

  findAll() {
    return `This action returns all userError`;
  }

  async findByUserId(userId:string):  Promise<[boolean, UserError[]]> {
    let result = await this.usersErrorRepository.find({ where: { user: {Id:userId} }, relations: ["exe", "user"] });
    if (!result) {
      return [false,[]];
    }
    return [true,result];
  }

  async update(updateUserErrorDto: CreateUserErrorDto):  Promise<[boolean, string]>{
    let result = await this.usersErrorRepository.findOne({ where: { user: {Id:updateUserErrorDto.userId}, exe: {Id:updateUserErrorDto.exeId} }, relations: ['exe', 'user'] });
    if (result) {
      result.errorCount+=1;
      result.lastErrorTime=updateUserErrorDto.lastErrorTime;
      await this.usersErrorRepository.save(result);
      return [true, "错题次数更新成功"];
    }else{
    
    const exe=new Exebook();
    exe.Id=updateUserErrorDto.exeId;
    const user=new User();
    user.Id=updateUserErrorDto.userId;
    const newUserError = this.usersErrorRepository.create(updateUserErrorDto);  
    newUserError.exe=exe;
    newUserError.user=user;
    newUserError.errorCount=1;
    newUserError.lastErrorTime=updateUserErrorDto.lastErrorTime;
    await this.usersErrorRepository.save(newUserError);
    
    return [true, "新错题记录创建成功"];
  }
    
  }

  remove(id: string) {
    const result = this.usersErrorRepository.delete(id);
    return `This action removes a #${id} userError`;
  }
}
